import { Component, ReactNode } from "react";
import {createPortal} from 'react-dom' 
import './index.css'

type Iprops = {
    title?: string; // 标题
    children?: ReactNode; //主体内容
    onOk?: () => void; //点击确定按钮
    onCancel?: () => void; // 点击取消按钮
    open?: boolean; // 控制显示和隐藏
}

// 声明类属性
type m={
    dv:HTMLElement
}

// 声明state类型
type Istate = {
    visible: boolean //组件内部状态，控制组件显示和隐藏
    isClose: boolean // 标记是否点击了xx
}
class Modal extends Component<Iprops, Istate>{
    state = {
        visible: false,
        isClose: false,
    }


    dv=document.createElement('div')
    // 一个全新的钩子函数，接收新的props和state
    static getDerivedStateFromProps(nextProps: Iprops, nextState: Istate): Object | null {
        // console.log(nextProps)
        // console.log(nextState);

        let { open } = nextProps
        let { visible, isClose } = nextState
        if (isClose) {
            // 点击了xx按钮
            return {
                visible,
                isClose: false //重置开关
            }
        } else {
            return {
                visible: open
            }
        }

    }

    componentDidMount(): void {
        this.dv.id='modal-root'
        document.body.appendChild(this.dv)
    }

    componentWillUnmount(): void {
        // 先判断页面上有没有modalRoot
        let modalRoot=document.getElementById('modal-root')
        modalRoot && document.body.removeChild(modalRoot)
    }

    // 点击叉叉关闭模态框
    handleClose = () => {
        this.setState({
            visible: false,
            isClose: true
        })
    }
    render(): ReactNode {
        let { visible } = this.state
        let {children,title,onOk,onCancel} =this.props
        let el = (
            <div className="modal-container">
                <div className="modal-mask">
                    <div className="modal-content">
                        <button onClick={this.handleClose} className="close">×</button>
                        <div className="header">
                            {title??'请君'}
                        </div>
                        <div className="body">
                            {children?children:'生活是各种颜色混合而成的黑'}
                        </div>
                        <div className="footer">
                            <button onClick={()=>{
                                onCancel && onCancel()
                            }} className="cancel">取消</button>
                            <button onClick={()=>{
                                onOk && onOk()
                            }} className="confirm">确定</button>
                        </div>
                    </div>
                </div>
            </div>
        )
        return visible ? createPortal(el,this.dv) : null
    }
}

export default Modal